import {Component, OnInit} from '@angular/core';
import {ArticleService} from "../../service/article.service";
import {Article} from "../../entity/article";
import {ToastyService, ToastOptions, ToastData} from 'ng2-toasty';

declare let wangEditor:any;

@Component({
    moduleId: module.id,
    selector: 'my-back-wztg',
    template: `<div class="row">
  <div class="col-sm-1"></div>
  <div class="col-sm-10" style="text-align: center;margin-bottom: 30px">
    <form (submit)="onSubmit()" #articleForm="ngForm">
      <div class="form-group row has-success">
        <label for="title" class="col-xs-2 form-control-label">标题</label>
        <div class="col-xs-10">
          <input [(ngModel)]="article.title" required name="title" class="form-control form-control-success" type="text"
                 id="title" placeholder="请输入文章标题" placement="top" minlength="5" ngbTooltip="文章标题长度应在5到50个字符之间">
        </div>
      </div>
      <hr>
      <div class="form-group row has-warning">
        <label for="synopsis" class="col-xs-2 form-control-label">简介</label>
        <div class="col-xs-10">
          <input [(ngModel)]="article.synopsis" required name="synopsis" class="form-control form-control-warning"
                 type="text" id="synopsis" placeholder="请输入文章简介" minlength="10" placement="top" ngbTooltip="文章简介长度应在10到255个字符之间">
        </div>
      </div>
      <hr>
      <div class="form-group row">
        <label class="col-xs-2 col-form-label">正文</label>
        <div class="col-xs-10">
          <div id="editor" style="height: 500px">
            <p>请填写文章正文。正文不得包含令人反感的信息，且长度应在10到65535个字符之间。</p>
          </div>
        </div>
      </div>
      <ngb-alert type="success" [dismissible]="false">
        确认文章信息无误后，点击下方左“提交投稿”按钮提交投稿。
      </ngb-alert>
      <hr>
      <button type="submit" [disabled]="!articleForm.form.valid" class="btn btn-primary">提交投稿</button>
    </form>
  </div>
  <div class="col-sm-1"></div>
</div>`,
    providers: [ArticleService]
})

export class BackItemArticleUploadComponent implements OnInit {

  editor:any;
  article = new Article();

  constructor(private articleService:ArticleService, private toastyService:ToastyService){};

  onSubmit(){
    this.article.content = this.editor.$txt.html();
    this.articleService.insertArticle(this.article);
    const toastOptions:ToastOptions = {
      title: "提示信息",
      msg: "发布文章成功！",
      showClose: true,
      timeout: 3000,
      theme: 'bootstrap',
      onAdd: (toast:ToastData) => {},
      onRemove: function(toast:ToastData) {}
    };
    this.toastyService.success(toastOptions);
  }

  ngOnInit(): void {
    this.editor = new wangEditor('editor');
    // 粘贴过滤
    this.editor.config.pasteFilter = true;
    this.editor.create();
  }
}
